package com.zxy.supplier_system.server.controller

import com.zxy.supplier_system.server.service.WechatUserInfoService
import com.zxy.supplier_system.server.utils.LoggerDelegate
import com.zxy.supplier_system.server.utils.wechat.official.WechatMessagePreValidateRequest
import com.zxy.supplier_system.server.utils.wechat.official.WechatOfficialAccountHelper
import com.zxy.supplier_system.server.utils.wechat.official.getUserInfo
import com.zxy.supplier_system.server.utils.wechat.official.parseWechatMessage
import com.zxy.supplier_system.server.utils.wechat.official.validateWechatMessagePreValidateRequest
import jakarta.servlet.http.HttpServletRequest
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.server.ResponseStatusException

@RestController
@RequestMapping("wechat/official/message/receive")
class WechatOfficialMessageReceiveController(
    private val wechatOfficialAccountHelper: WechatOfficialAccountHelper,
    private val wechatUserInfoService: WechatUserInfoService,
) {

    companion object{
        private val log by LoggerDelegate()
    }

    @GetMapping
    fun validate(request: WechatMessagePreValidateRequest): String {
        if (wechatOfficialAccountHelper.validateWechatMessagePreValidateRequest(request)){
            return request.echostr
        }else {
            throw ResponseStatusException(HttpStatus.BAD_REQUEST,"校验失败 + $request")
        }
    }

    @PostMapping(consumes = [MediaType.APPLICATION_XML_VALUE], produces = [MediaType.APPLICATION_XML_VALUE])
    fun receive(request: HttpServletRequest): String {
        val messageBody = wechatOfficialAccountHelper.parseWechatMessage(request)
        log.debug("收到来自微信的消息:{}",messageBody)
        if (messageBody["MsgType"]=="event"){
            if (messageBody["Event"]=="subscribe"){
                val openId = messageBody["FromUserName"] as String
                val userInfo = wechatOfficialAccountHelper.getUserInfo(openId)
                if (userInfo.unionid!=null){
                    wechatUserInfoService.saveFromOfficialAccountOpenIdAndUnionId(userInfo.openid,userInfo.unionid)
                }
            }
        }

        return ""
    }

}